package com.acxy.ants.resful;

import com.acxy.ants.core.config.Modules;
import com.acxy.ants.resful.annotation.Controller;
import com.acxy.ants.core.kit.ScanKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author MrShun
 * @version 1.0
 * @Date 2017-04-27
 */
final public class Mapping {

    private static final Logger logger = LoggerFactory.getLogger(Mapping.class);

    private static final List<RequestMapping> Mappings = new ArrayList<>();


    public static List<RequestMapping> registerMappings(String packages, String regexSuffix, boolean isDebug) {
        if (Mappings == null || Mappings.size() == 0) {
            List<Class<?>> classesList = (packages == null) ? ScanKit.getAnnotatedClass(Controller.class) : ScanKit.getAnnotatedClass(packages, Controller.class);
            logger.debug("初始化[controller]层 ...");
            List<RequestMapping> requestMappingList = ActionInitialization.getRequestMappingList(classesList, regexSuffix, null);
            for (RequestMapping requestMapping : requestMappingList) {
                if (isDebug) logger.debug(">>> {} :: Generator Success !", requestMapping.toString());
                Mappings.add(requestMapping);
            }

            Map<String, List<Class<?>>> moduleControllerMap = Modules.getModuleControllerMap();
            if(moduleControllerMap != null || moduleControllerMap.size() !=0){
                for (Map.Entry<String, List<Class<?>>> entry: moduleControllerMap.entrySet()) {
                    String moduleName = entry.getKey();
                    logger.debug("[{}] 模块初始化[controller]层开始 ...", moduleName);
                    List<RequestMapping> requestModuleMappingList = ActionInitialization.getRequestMappingList(entry.getValue(), regexSuffix, moduleName);
                    for (RequestMapping requestMapping : requestModuleMappingList) {
                        if (isDebug) logger.debug(">>> {} :: Generator Success !", requestMapping.toString());
                        Mappings.add(requestMapping);
                    }
                    logger.debug("[{}] 模块初始化[controller]层完成 ...", moduleName);
                }
            }
        }
        return Mappings;
    }

    public static List<RequestMapping> getMappings(){
        return Mappings;
    }
}
